package com.maserb.monitor.web.jw_question;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.jwQuestion.*;
import com.maserb.monitor.enums.JwEducationStautsEnum;
import com.maserb.monitor.enums.JwQuestionStatusEnum;
import com.maserb.monitor.enums.JwQuestionWinningEnum;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.jwQuestion.JwQuestionItemUserService;
import com.maserb.monitor.service.jwQuestion.JwQuestionOptionUserService;
import com.maserb.monitor.service.jwQuestion.JwQuestionService;
import com.maserb.monitor.service.jwQuestion.JwQuestionUserService;
import com.maserb.monitor.service.system_manage.EigenValueDictionaryService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/jwQuestion")
public class JwQuestionController {



    @Autowired
    JwQuestionService jwQuestionService;

    @Autowired
    JwQuestionUserService questionUserService;

    @Autowired
    private JwQuestionItemUserService questionItemUserService;

    @Autowired
    private JwQuestionOptionUserService questionOptionUserService;


    @Autowired
    private IToolService toolService;

    @Autowired
    private JwOrgService orgService;

    @Autowired
    EigenValueDictionaryService eigenValueDictionaryService;

    @RequestMapping(value = {"/", "/index"})
    public ModelAndView getIndex(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("jw_question/index");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = "";
        String schoolId = "";
        if(null!=user && !StringUtils.isEmptyOrWhitespace(user.getId())){
            userId = user.getId();
            if(!StringUtils.isEmptyOrWhitespace(user.getOrgId())){
                schoolId = user.getOrgId();
            }
        }
        JwQuestionStatusEnum[] isReleasEnums = JwQuestionStatusEnum.values();
        JwEducationStautsEnum[] stautsEnums = JwEducationStautsEnum.values();
        view.addObject("isReleasEnums",isReleasEnums);
        view.addObject("stautsEnums",stautsEnums);
        view.addObject("userId",userId);
        view.addObject("schoolId",schoolId);
        return view;
    }

    @RequestMapping("/doListQuestion")
    @ResponseBody
    public PageResponseResult<JwQuestionEntity> doListQuestion(PageRequestParam page,String schoolId, final String name,final String status ,final String isTop) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        Sort.Order favoritesOrder = new Sort.Order(Sort.Direction.DESC, "favorites");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(favoritesOrder);
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<JwQuestionEntity>>() {
            @Override
            public Page<JwQuestionEntity> invoke(PageRequest var1) throws Exception {
                Page<JwQuestionEntity> jwQuestionEntityPage = jwQuestionService.findAll(var1,schoolId, name ,status,isTop);
                for(JwQuestionEntity entity:jwQuestionEntityPage.getContent()){
                    entity.setCreateTime(toolService.formatYYMMDDHHMMSS(entity.getCreateTime()));
                    if(null!=entity.getStatus() && !"".equals(entity.getStatus())) {
                        entity.setStatus(JwQuestionStatusEnum.getNameByValue(Integer.parseInt(entity.getStatus())));
                    }
                    if(null!=entity.getIsTop() && !"".equals(entity.getIsTop())) {
                        entity.setIsTop(JwEducationStautsEnum.getNameByValue(Integer.parseInt(entity.getIsTop())));
                    }
                    if(!StringUtils.isEmptyOrWhitespace(entity.getSchoolId())){
                        entity.setSchoolId(toolService.getOrgName(entity.getSchoolId()));
                    }
                }
                return jwQuestionEntityPage;
            }
        });
    }

    @RequestMapping(value = "/indexUser")
    public ModelAndView getIndexUser(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("jw_question/question_user_index");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = "";
        String schoolId = "";
        if(null!=user && !StringUtils.isEmptyOrWhitespace(user.getId())){
            userId = user.getId();
            if(!StringUtils.isEmptyOrWhitespace(user.getOrgId())){
                schoolId = user.getOrgId();
            }
        }
        JwQuestionWinningEnum[] infoWinning = JwQuestionWinningEnum.values();
        view.addObject("infoWinning",infoWinning);
        view.addObject("userId",userId);
        view.addObject("schoolId",schoolId);
        return view;
    }

    //获取已完成的问卷调查
    @RequestMapping("/doListFinished")
    @ResponseBody
    public PageResponseResult<JwQuestionUserEntity> doListFinished(PageRequestParam page,String name,String schoolId) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page, sort,new Func_T1<PageRequest, Page<JwQuestionUserEntity>>() {
            @Override
            public Page<JwQuestionUserEntity> invoke(PageRequest var1) throws Exception {
                Page <JwQuestionUserEntity> page = questionUserService.findAll(var1,name,schoolId);
                for(JwQuestionUserEntity entity:page.getContent()){
                    entity.setCreateTime(toolService.formatYYMMDDHHMMSS(entity.getCreateTime()));
                    if(!StringUtils.isEmptyOrWhitespace(entity.getSchoolId())){
                        entity.setSchoolId(toolService.getOrgName(entity.getSchoolId()));
                    }
                }
                return page;
            }
        });
    }

    //查看已完成的问卷调查详情
    @RequestMapping("/getViewQuestionFinished/{id}")
    public ModelAndView getViewQuestionFinished(@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        JwQuestionUserEntity userEntity = questionUserService.findOne(id);

        String jwQuestionUserId = userEntity.getId();
        List<JwQuestionItemUserEntity>itemUserList=questionItemUserService.findByQuestionUserId(jwQuestionUserId);
        List<JwQuestionOptionUserEntity>optionUserList=questionOptionUserService.findByQuestionUserId(jwQuestionUserId);
        Map<String,String> itemMap = new<String,String>HashMap();
        for(JwQuestionItemUserEntity itemUser : itemUserList){
            if("3".equals(itemUser.getType())){
                itemMap.put(itemUser.getQuestionItemId(),itemUser.getQuestionValue());
            }
        }
        StringBuilder optionUserStr = new StringBuilder();
        for(JwQuestionOptionUserEntity optionUser:optionUserList){
            optionUserStr.append(optionUser.getQuestionOptionId()+",");
        }
        JwQuestionEntity entity = jwQuestionService.findOne(userEntity.getQuestionId());
        for(JwQuestionItemEntity item : entity.getItems()){
            if(itemMap.containsKey(item.getId())){
                item.setDescription(itemMap.get(item.getId()));
            }
            for(JwQuestionOptionEntity option :item.getOptions()){
                if(optionUserStr.indexOf(option.getId())!=-1){
                    option.setIsSelected(1);
                }
            }
        }
        result.setViewName("jw_question/question_finished_view");
        result.addObject("entity", entity);
        return result;
    }


    @RequestMapping("/getAddQuestion")
    public ModelAndView getAddQuestion() {
        ModelAndView result = new ModelAndView();
        result.setViewName("jw_question/add");
        return result;
    }

    @RequestMapping("/doAddQuestion")
    @ResponseBody
    public AjaxResult<Boolean> doAddQuestion(final HttpServletRequest request, JwQuestionEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                entity.setStatus("0");
                entity.setIsDel("0");
                entity.setIsTop("0");
                entity.setFavorites(0);
                HttpSession session = request.getSession(true);
                UserEntity userEntity = (UserEntity) session.getAttribute("user");
                if(null!=userEntity && !StringUtils.isEmptyOrWhitespace(userEntity.getOrgId())){
                    entity.setSchoolId(userEntity.getOrgId());
                }
                jwQuestionService.save(entity);
                return true;
            }
        });
    }


    //导出
    @RequestMapping("/getExportQuestion")
    public void getExportQuestion( HttpServletResponse response,@RequestParam String id) {
        JwQuestionEntity questionEntity = jwQuestionService.findOne(id);
        List<JwQuestionItemEntity> list =questionEntity.getItems();
        String name=questionEntity.getName();
        int count = questionEntity.getCount();
        String fileName="";
        String title="";
        try{
            fileName  = name + System.currentTimeMillis()+".xls";
            title = name+"——测评人数:"+count+"人";
        }catch (Exception e){
            e.printStackTrace();
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title,name),
                JwQuestionItemEntity.class, list);
        ExcelExportUtils.downLoadExcel(fileName, response, workbook);
    }



    //导入
    @RequestMapping("/goFileUpload")
    public ModelAndView goFileUpload() {
        ModelAndView result = new ModelAndView();
        result.setViewName("jw_question/question_import");
        return result;
    }


    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(final HttpServletRequest request,HttpServletResponse response, MultipartFile myfiles) throws IOException{
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(2);
        params.setNeedVerfiy(true);
        String resultStr = "导入成功";
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(myfiles.getInputStream(),JwQuestionItemEntity.class,params);
            List<JwQuestionItemEntity> list = result.getList();
            Sheet sheet = result.getWorkbook().getSheetAt(0);
            String sheetName = sheet.getSheetName();
            String title =sheet.getRow(0).getCell(0).getStringCellValue();
            HttpSession session = request.getSession(true);
            UserEntity user = (UserEntity) session.getAttribute("user");
            String schoolId = "";
            if(null!=user && !StringUtils.isEmptyOrWhitespace(user.getId())){
                if(!StringUtils.isEmptyOrWhitespace(user.getOrgId())){
                    schoolId = user.getOrgId();
                }
            }
            jwQuestionService.saveImport(title,list,schoolId);
        } catch (Exception e) {
            return "导入失败！";
        }
        return resultStr;
    }

    //查看
    @RequestMapping("/getViewQuestion/{id}")
    public ModelAndView getViewQuestion(@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        JwQuestionEntity entity = jwQuestionService.findOne(id);
        result.setViewName("jw_question/question_view");
        result.addObject("entity", entity);
        return result;
    }

    //修改页面跳转
    @RequestMapping("/getUpdateQuestion/{id}")
    public ModelAndView getUpdateQuestion(@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        JwQuestionEntity entity = jwQuestionService.findOne(id);
        result.setViewName("jw_question/question_edit");
        result.addObject("entity", entity);
        return result;
    }

    //修改
    @RequestMapping("/doUpdateQuestion")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateQuestion(final HttpServletRequest request, JwQuestionEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                JwQuestionEntity jwQuestionEntity = jwQuestionService.findOne(entity.getId());
                jwQuestionEntity.setName(entity.getName());
                jwQuestionEntity.setImage(entity.getImage());
                jwQuestionEntity.setDescription(entity.getDescription());
                jwQuestionEntity.setUpdateTime(CreateTimeUtils.getCreateTime());
                jwQuestionService.save(jwQuestionEntity);
                return true;
            }
        });
    }

    //删除
    @RequestMapping("/doDeleteQuestion")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteQuestion(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> jwQuestionService.dodelete(id));
                return true;
            }
        });
    }

    //发布(推送新的测评到手机端)
    @RequestMapping("/doRelease")
    @ResponseBody
    public AjaxResult<Boolean> doRelease(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> jwQuestionService.doRelease(id));
                return true;
            }
        });
    }

    //结束测评
    @RequestMapping("/doDisabled")
    @ResponseBody
    public AjaxResult<Boolean> doDisabled(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> jwQuestionService.doDisabled(id));
                return true;
            }
        });
    }

    //置顶
    @RequestMapping("/doTop")
    @ResponseBody
    public AjaxResult<Boolean> doTop(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> jwQuestionService.doTop(id));
                return true;
            }
        });
    }

    //取消置顶
    @RequestMapping("/cancelTop")
    @ResponseBody
    public AjaxResult<Boolean> cancelTop(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> jwQuestionService.cancelTop(id));
                return true;
            }
        });
    }

}
